<template>
	<view class="page quotation-add">
		<!-- 基本信息 -->
		<view class="title">基本信息</view>
		<view class="panel">
			<com-form ref="formItem" :key="curDate" :form="formList.baseinfo" :fields="fieldList.baseinfo" :rules="ruleList.baseinfo" @onChange="baseFromChange"></com-form>
		</view>

		<!-- 甲方信息 -->
		<view class="title">甲方信息</view>
		<view class="panel">
			<com-form ref="formItem" :key="curDate" :form="formList.partA" :fields="fieldList.partA" :rules="ruleList.partA" @onChange="partAChange"></com-form>
		</view>

		<!-- 乙方信息 -->
		<view class="title">乙方信息</view>
		<view class="panel">
			<com-form ref="formItem" :key="curDate" :form="formList.partB" :fields="fieldList.partB" :rules="ruleList.partB" @onChange="partBChange"></com-form>
		</view>

		<!-- 付款节点及金额 -->
		<view class="title">付款节点及金额 （最多添加5个付款节点）</view>
		<view class="panel">
			<payment-info ref="formItem" :key="curDate" :money="finalMoney" :list="paymentList" @onChange="paymentChange"></payment-info>
		</view>

		<!-- 开票节点及金额 -->
		<view class="title">开票节点及金额 （最多添加5个开票节点）</view>
		<view class="panel">
			<invoice-info ref="formItem" :key="curDate" :money="finalMoney" :list="invoiceList" @onChange="invoiceChange"></invoice-info>
		</view>

		<!-- 甲方开票信息 -->
		<view class="title">甲方开票信息</view>
		<view class="panel">
			<com-form ref="formItem" :key="curDate" :form="formList.invoice" :fields="fieldList.invoice" :rules="ruleList.invoice" @onChange="partAInvoiceChange"></com-form>
		</view>

		<!-- 产品交付与验收 -->
		<view class="title">产品交付与验收</view>
		<view class="panel">
			<com-form ref="formItem" :key="curDate" :form="formList.pdaa" :fields="fieldList.pdaa" :rules="ruleList.pdaa" @onChange="pdaaChange"></com-form>
		</view>

		<!-- 质量保证、保修及服务期限 -->
		<view class="title">质量保证、保修及服务期限</view>
		<view class="panel">
			<com-form ref="formItem" :key="curDate" :form="formList.qas" :fields="fieldList.qas" :rules="ruleList.qas" @onChange="qasChange"></com-form>
		</view>

		<!-- 审核信息 -->
		<examine-info type="1"></examine-info>

		<!-- 按钮 -->
		<footer-bar>
			<u-button type="primary" @click="save(1)">提交审核</u-button>
			<u-button type="warning" @click="save(2)">保存草稿</u-button>
			<u-button type="error" @click="save(3)">取消</u-button>
		</footer-bar>
	</view>
</template>

<script>
import dayjs from 'dayjs';

// 通用表单信息
import comForm from './components/comForm';
// 付款节点及金额
import paymentInfo from './components/paymentInfo';
// 通用表单信息
import invoiceInfo from './components/invoiceInfo';
// 审核信息
import examineInfo from '../common/examineInfo';
// 操作按钮
import footerBar from '../common/footerBar';
export default {
	components: {
		comForm,
		paymentInfo,
		invoiceInfo,
		examineInfo,
		footerBar,
	},
	data: () => ({
		// 当前id
		id: 0,
		curDate: 1,
		// 表单
		formList: {
			baseinfo: {},
			partA: {},
			partB: {},
			invoice: {},
			pdaa: {},
			qas: {},
			other: {},
		},
		// 表单校验规则
		ruleList: {
			baseinfo: {},
			partA: {},
			partB: {},
			invoice: {},
			pdaa: {},
			qas: {},
			other: {},
		},
		// 表单字段
		fieldList: {
			// 基本信息
			baseinfo: [],
			// 甲方信息
			partA: [
				{
					fieldName: 'partACompanyName',
					name: '公司名称',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partACompanyAddress',
					name: '通讯地址',
					formType: 'textarea',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partACompanyContactName',
					name: '联系人姓名',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partACompanyPhone',
					name: '联系人电话',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partACompanyFax',
					name: '传真',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 0,
				},
				{
					fieldName: 'partACompanyEmail',
					name: '邮箱',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 0,
				},
			],
			// 乙方信息
			partB: [
				{
					fieldName: 'partBCompanyName',
					name: '公司名称',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partBCompanyAddress',
					name: '通讯地址',
					formType: 'textarea',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partBCompanyContactName',
					name: '联系人姓名',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partBCompanyPhone',
					name: '联系人电话',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partBCompanyFax',
					name: '传真',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 0,
				},
				{
					fieldName: 'partBCompanyEmail',
					name: '邮箱',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 0,
				},
			],
			// 甲方开票信息
			invoice: [
				{
					fieldName: 'partCompanyName',
					name: '公司名称',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partCompanyTaxNumber',
					name: '公司税号',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partCompanyAddress',
					name: '注册地址',
					formType: 'textarea',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partCompanyBank',
					name: '开户银行',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partCompanyBankAccount',
					name: '银行账号',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'partCompanyPhone',
					name: '电话号码',
					formType: 'text',
					value: '',
					defaultValue: '',
					isNull: 1,
				},
			],
			// 产品交付与验收
			pdaa: [
				{
					fieldName: 'hardwareDeliveryConditions',
					name: '发货条件',
					formType: 'autocomplete',
					value: '',
					setting: [],
					defaultValue: '',
					isNull: 1,
				},
				{
					fieldName: 'hardwareDeliveryCycle',
					name: '发货周期（天）',
					formType: 'number',
					value: '',
					defaultValue: 2,
					isNull: 1,
				},
				{
					fieldName: 'hardwareFreightBearer',
					name: '运费承担者',
					formType: 'select',
					value: '',
					setting: ['甲方', '乙方'],
					defaultValue: '乙方',
					isNull: 1,
				},
				{
					fieldName: 'hardwareReceivingCycle',
					name: '收货周期（天）',
					formType: 'number',
					value: '',
					defaultValue: 2,
					isNull: 1,
				},
				{
					fieldName: 'hardwareWrittenNotificationPeriod',
					name: '书面通知周期（天）',
					formType: 'number',
					value: '',
					defaultValue: 2,
					isNull: 1,
				},
				{
					fieldName: 'hardwareConfirmationLeadTime',
					name: '交付周期（天）',
					formType: 'number',
					value: '',
					defaultValue: 2,
					isNull: 1,
				},
				{
					fieldName: 'softwareTrainingCycle',
					name: '软件培训周期（天）',
					formType: 'number',
					value: '',
					defaultValue: 2,
					isNull: 1,
				},
			],
			// 质量保证、保修及服务期限
			qas: [
				{
					fieldName: 'warrantyPeriod',
					name: '保修期（月）',
					formType: 'number',
					value: '',
					defaultValue: 12,
					isNull: 1,
				},
				{
					fieldName: 'warrantyMethod',
					name: '保修方式',
					formType: 'text',
					value: '',
					defaultValue: '交换式',
					isNull: 1,
				},
				{
					fieldName: 'serviceTerm',
					name: '服务期限（月）',
					formType: 'number',
					value: '',
					defaultValue: 12,
					isNull: 1,
				},
				{
					fieldName: 'onSiteResponseCycle',
					name: '到场响应周期（H）',
					formType: 'number',
					value: '',
					defaultValue: 36,
					isNull: 1,
				},
			],
			// 一般条款
			other: [
				{
					fieldName: 'numberContracts',
					name: '合同份数',
					formType: 'number',
					value: '',
					defaultValue: 2,
					isNull: 1,
					type: 'other',
				},
				{
					fieldName: 'numberCopies',
					name: '各执份数',
					formType: 'text',
					value: '',
					defaultValue: 1,
					isNull: 1,
					type: 'other',
				},
			],
		},
		// 付款节点及金额 付款条件
		paymentConditionOptions: [
			{ label: '合同签订后', value: '合同签订后' },
			{ label: '现场实施后', value: '现场实施后' },
			{ label: '项目验收后', value: '项目验收后' },
		],
		// 禁用按钮
		checkList: {
			paymentIsAll: false,
			invoiceIsAll: false,
		},
		// 联系信息
		contractInfo: {},
		// 开票节点及金额
		invoiceList: [],
		// 付款节点及金额
		paymentList: [],
		// 甲方开票信息
		partInvoice: {},
		// 总价
		finalMoney: 0,
		cache: {
			customerId: '',
			quotationId: '',
		},
	}),
	methods: {
		// 获取基本信息字段
		async getFields() {
			let data = {
				label: 6,
			};

			// 编辑的时候传入参数
			this.id > 0 && (data.id = this.id);

			let res = await this.$api.customer.common.fields(data);
			if (res.code === 200) {
				let list = res.data || [];
				this.fieldList.baseinfo = list;

				list.forEach((v, k) => {
					// 设置表单
					if (this.id > 0) {
						// 编辑回显
						if (v.fieldName === 'customer_id') {
							this.formList.baseinfo[v.fieldName] = v.value[0].customerName;
							this.fieldList.baseinfo[k].valueKey = v.value[0].customerId;
						} else if (v.fieldName === 'quotation_id') {
							this.formList.baseinfo[v.fieldName] = v.value[0].quotationNumber;
							this.fieldList.baseinfo[k].valueKey = v.value[0].quotationId;
						} else if (v.fieldName === 'business_id') {
							this.formList.baseinfo[v.fieldName] = v.value[0].businessName;
							this.fieldList.baseinfo[k].valueKey = v.value[0].businessId;
						} else {
							this.formList.baseinfo[v.fieldName] = v.value || '';
						}
					} else {
						this.formList.baseinfo[v.fieldName] = v.value;
					}

					// 设置校验规则
					if (v.isNull == 1) {
						this.ruleList.baseinfo[v.fieldName] = {
							required: true,
							message: v.inputTips || v.name + '不能为空',
							trigger: ['blur', 'change'],
						};
					}

					// 设置日期
					let month = ('0' + (dayjs().month() + 1)).slice(-2);
					let date = ('0' + dayjs().date()).slice(-2);
					this.formList.baseinfo.order_date = dayjs().year() + '-' + month + '-' + date;
				});
			}
		},
		// 初始化各个表单字段信息
		initFormList() {
			let forms = Object.keys(this.fieldList);

			forms.forEach((form) => {
				if (form !== 'baseinfo') {
					this.fieldList[form].forEach((field) => {
						this.formList[form][field.fieldName] = '';
					});
				}
			});
		},
		// 获取联系信息
		async getContact(customerId) {
			let data = {
				customerId: customerId,
			};
			let res = await this.$api.customer.contract.contacts(data);

			// 设置甲方信息
			const newVal = {
				partACompanyName: res.customerInfo.customerName,
				partACompanyAddress: res.customerInfo.address,
				partACompanyContactName: res.data.list[0].name || '',
				partACompanyPhone: res.data.list[0].mobile || '',
			};
			this.formList.partA = Object.assign(this.formList.partA, newVal);
			// 设置key，刷新数据
			this.curDate = new Date().getTime();
		},
		// 获取甲方信息
		async getPartACompany(customerId) {
			let data = {
				customerId: customerId,
			};
			let res = await this.$api.customer.contract.partACompany(data);

			if (res.code === 200) {
				let data = { ...res.data };
				delete data.customerId;
				// 设置甲方开票信息
				this.formList.invoice = Object.assign(this.formList.invoice, data);
				// 设置key，刷新数据
				this.curDate = new Date().getTime();
			}
		},
		// 获取企业信息和报价信息
		async getCompanyAndQuotation(quotationId) {
			let data = {
				quotationId: quotationId,
			};
			console.log(data);
			let res = await this.$api.customer.contract.companyAndQuotation(data);

			if (res.code === 200) {
				let resData = { ...res.data };
				let newVal = {
					money: resData.finalSalesPriceTax,
					sign_location: resData.companyArea,
					rate: resData.rate,
				};
				// 设置基本信息
				this.formList.baseinfo = Object.assign(this.formList.baseinfo, newVal);
				// 设置乙方信息
				let userInfo = uni.getStorageSync('userInfo');
				let partB = {
					partBCompanyName: resData.companyName,
					partBCompanyAddress: resData.address,
					partBCompanyContactName: userInfo.realname,
					partBCompanyPhone: userInfo.mobile,
				};
				this.formList.partB = Object.assign(this.formList.partB, partB);
				// // 设置key，刷新数据
				this.curDate = new Date().getTime();
			}
		},
		// 基本信息表单改变事件
		baseFromChange(data) {
			console.log(data);
			if (data.customer_id && this.cache.customerId !== data.customer_id) {
				// 缓存id，防止重复请求数据
				this.cache.customerId = data.customer_id;
				// 根据客户id获取联系信息
				this.getContact(data.customer_id);
				// 根据客户id获取甲方信息
				this.getPartACompany(data.customer_id);
			}

			if (data.quotation_id && this.cache.quotationId !== data.quotation_id) {
				// 缓存id，防止重复请求数据
				this.cache.quotationId = data.quotation_id;
				// 加载并设置数据
				this.getCompanyAndQuotation(data.quotation_id);
			}
		},
		// 甲方信息
		partAChange(data) {},
		// 乙方信息
		partBChange(data) {},
		// 付款节点及金额
		paymentChange(data) {},
		// 开票节点及金额
		invoiceChange(data) {},
		// 甲方开票信息
		partAInvoiceChange(data) {},
		// 产品交付与验收
		pdaaChange(data) {},
		// 质量保证、保修及服务期限
		qasChange(data) {},
		// 保存数据
		async save(type) {
			if ([1, 2].includes(type)) {
				// 提交审核
				let data = {
					// 附件
					annexList: [],
					field: [],
					businessInfo: {},
					entity: { ...this.formList.baseinfo },
					// 联系信息
					contractInfo: { ...this.contractInfo },
					// 开票节点及金额
					invoiceList: [...this.invoiceList],
					// 付款节点及金额
					paymentList: [...this.paymentList],
					// 甲方开票信息
					partInvoice: { ...this.partInvoice },
				};
				// 保存草稿
				if (type === 2) {
					data.entity.checkStatus = 5;
				}
				// 如果是编辑带上id
				if (this.id) {
					data.entity.contractId = this.id;
				}

				// 校验
				let res = await this.$api.customer.contract.save(data);
				if (res.code === 200) {
					uni.showToast({
						icon: 'none',
						title: '操作成功',
					});
					// 返回上一页
					uni.navigateBack({
						delta: 1,
					});
				}
			}
			if (type == 3) {
				// 取消，返回上一页
				// 返回列表
				uni.navigateBack({
					delta: 1,
				});
			}
		},
	},
	computed: {},
	watch: {},

	// 周期函数--监听页面加载
	onLoad(options) {
		this.id = options.id ? options.id : 0;
	},
	// 周期函数--监听页面初次渲染完成
	onReady() {},
	// 周期函数--监听页面显示
	onShow() {
		if (this.id) {
			uni.setNavigationBarTitle({
				title: '编辑合同清单',
			});
		}
		this.getFields();
		this.initFormList();
	},
	// 周期函数--监听页面隐藏
	onHide() {},
	// 周期函数--监听页面卸载
	onUnload() {},
	// 页面处理函数--监听用户下拉动作
	onPullDownRefresh() {},
	// 页面处理函数--监听用户上拉触底
	onReachBottom() {},
	// 页面处理函数--监听页面滚动
	/* onPageScroll(event) {}, */
	// 页面处理函数--用户点击右上角分享
	/* onShareAppMessage(options) {}, */
};
</script>

<style lang="scss" scoped>
.page {
	background: #efefef;
}
.mb20 {
	margin-bottom: 20px;
}
.title {
	padding: 15px 15px 10px;
}
.panel {
	background: #fff;
	padding: 0 15px;

	/deep/ .panel-title {
		padding: 15px 0;
	}
}

.u-select /deep/ .u-drawer,
.u-drawer {
	z-index: 998 !important;
}
.u-field {
	padding: 10px 14px;
	color: #303133;

	.u-field-inner {
		display: flex;
	}

	.u-label {
		width: 65px;
	}
}

.footer {
	height: 80px;

	.inner {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 10;

		.btn {
			display: flex;
			padding: 10px;
			.u-btn {
				flex: 1;
				margin: 0;
				border-radius: 30px;
				padding: 0 12px;
				border: 0;
				margin: 10px;
				&:after {
					border-radius: 30px;
				}
			}
		}
	}
}
</style>
